const { Sequelize } = require('sequelize');
const path = require('path');
const fs = require('fs').promises;
const logger = require('../utils/logger');
const dotenv = require('dotenv');
const bcrypt = require('bcryptjs');

// 加载环境变量
dotenv.config({ path: path.join(__dirname, '../.env') });

async function initDatabase() {
  let sequelize;
  try {
    logger.info('开始初始化系统...');

    // 使用配置的数据库连接信息
    sequelize = new Sequelize({
      host: process.env.DB_HOST,
      port: process.env.DB_PORT || 3306,
      dialect: 'mysql',
      username: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      logging: msg => logger.debug(msg),
      timezone: '+08:00',
      define: {
        timestamps: true,
        underscored: true,
        charset: 'utf8mb4'
      },
      dialectOptions: {
        charset: 'utf8mb4',
        multipleStatements: true
      }
    });

    // 测试连接
    await sequelize.authenticate();
    logger.info('数据库连接成功');

    // 先删除所有表
    await sequelize.query('SET FOREIGN_KEY_CHECKS = 0');
    await sequelize.query('DROP TABLE IF EXISTS admins');
    await sequelize.query('DROP TABLE IF EXISTS fields');
    await sequelize.query('DROP TABLE IF EXISTS certificates');
    await sequelize.query('DROP TABLE IF EXISTS departments');
    await sequelize.query('DROP TABLE IF EXISTS permission_templates');
    await sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
    logger.info('旧表删除完成');

    // 加载所有模型
    const Admin = require('../models/Admin');
    const Field = require('../models/Field');
    const Department = require('../models/department');
    const Certificate = require('../models/Certificate');
    const PermissionTemplate = require('../models/PermissionTemplate');

    // 创建表结构
    await PermissionTemplate.sync({ force: true });
    await Field.sync({ force: true });
    await Admin.sync({ force: true });
    await Department.sync({ force: true });
    await Certificate.sync({ force: true });
    logger.info('数据库表创建完成');

    // 删除多余的索引
    try {
      await sequelize.query('ALTER TABLE admins DROP INDEX username');
      await sequelize.query('ALTER TABLE certificates DROP INDEX idx_sequence_number');
      logger.info('多余的索引已删除');
    } catch (error) {
      logger.warn('删除索引失败，可能索引不存在');
    }

    // 重新创建必要的索引
    try {
      await sequelize.query('ALTER TABLE certificates ADD UNIQUE INDEX `idx_sequence_number` (`sequence_number`)');
      logger.info('创建证书序号索引成功');
    } catch (error) {
      logger.warn('创建索引失败，可能索引已存在');
    }

    // 创建默认字段
    await Field.ensureCertNumberField();
    logger.info('默认字段创建完成');

    // 创建默认管理员账户
    await Admin.create({
      username: 'admin',
      password: 'admin123',
      name: '系统管理员'
    });
    logger.info('默认管理员账户创建完成');

    // 创建系统预设权限模板
    await PermissionTemplate.createSystemTemplates();
    logger.info('系统预设权限模板创建完成');

    // 创建根部门
    await Department.createRootDepartment();
    logger.info('根部门创建完成');

    // 创建必要的目录
    const dirs = [
      path.join(__dirname, '../uploads'),
      path.join(__dirname, '../uploads/qrcodes'),
      path.join(__dirname, '../uploads/imports'),
      path.join(__dirname, '../uploads/exports'),
      path.join(__dirname, '../logs')
    ];

    for (const dir of dirs) {
      await fs.mkdir(dir, { recursive: true });
    }
    logger.info('系统目录创建完成');

    logger.info('系统初始化完成！');
    logger.info('默认管理员账户：');
    logger.info('用户名：admin');
    logger.info('密码：admin123');
    
    process.exit(0);
  } catch (error) {
    logger.error('初始化失败:', error);
    if (sequelize) {
      await sequelize.close();
    }
    process.exit(1);
  }
}

// 执行初始化
initDatabase(); 